package com.example.wanshengtv;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

import android.app.Activity;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;

import com.bin.david.form.component.TableTitle;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.bg.BaseBackgroundFormat;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.MapTableData;
import com.bin.david.form.data.table.TableData;
import com.example.wanshengtv.bean.TVBaoGong;
import com.example.wanshengtv.bean.TVBaoGongMX;
import com.example.wanshengtv.bean.TVBaoGongTotal;
import com.example.wanshengtv.http.api.TVBaoGongApi;
import com.example.wanshengtv.http.api.TVBaoGongTotalApi;
import com.example.wanshengtv.http.model.HttpData;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends Activity implements LifecycleOwner, OnHttpListener {
    private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this);
    private SmartTable table;
    private TextView 当前在转流转卡;
    private TextView 当前在产数量;
    private TextView time;
    private TextView 今日投产数量;
    private TextView 今日半成品完工数量;
    private TextView 今日成品完工数量;
    private List<TVBaoGong> tvBaoGongMXList = new ArrayList<>();
    CompositeDisposable compositeDisposable = new CompositeDisposable();

    //动态设置colum
    //普通列
    MyFormat myFormat = new MyFormat();
    Column<String> column1 = new Column<>("", "工序名称");
    Column<Integer> column2 = new Column<>("报工数量", "报工数量");
    Column<Integer> column3 = new Column<>("误差数", "不良数量");
    Column<Integer> column4 = new Column<>("总数", "总数");
    Column<Integer> columnlastDay = new Column<>("昨日", "昨日");
    Column<Integer> column5 = new Column<>("30日均值(报工)", "日均值");
    Column<Integer> column6 = new Column<>("流转卡数", "流转卡数");
    Column<Integer> column7 = new Column<>("待产数量", "待产数量");
    Column<Integer> column8 = new Column<>("滞留(8小时)", "滞留警告");
    Column<Integer> column9 = new Column<>("质量控制", "质量控制");
    List<TVBaoGong> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        //查找控件
        table = findViewById(R.id.table);
        当前在转流转卡 = findViewById(R.id.当前在转流转卡);
        当前在产数量 = findViewById(R.id.当前在产数量);
        time = findViewById(R.id.time);
        今日投产数量 = findViewById(R.id.今日投产数量);
        今日半成品完工数量 = findViewById(R.id.今日半成品完工数量);
        今日成品完工数量 = findViewById(R.id.今日成品完工数量);

//        table.getTableTitle().setSize(30);

        //配置表格样式
        table.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {
            @Override
            public int getBackGroundColor(CellInfo cellInfo) {
                if (cellInfo.row % 2 == 1) {
                    return ContextCompat.getColor(MainActivity.this, R.color.arc_bg);
                }
                return ContextCompat.getColor(MainActivity.this, R.color.white);
                //return TableConfig.INVALID_COLOR;
            }

        }).setShowXSequence(false).setShowYSequence(false).setContentStyle(new FontStyle().setTextColor(getResources().getColor(R.color.base_black_title_color)))
                .setVerticalPadding(6).setHorizontalPadding(0)
//                .setColumnTitleHorizontalPadding(34)
                .setColumnTitleBackground(new BaseBackgroundFormat(getResources().getColor(R.color.arc_bg)))
//                .setTableTitleStyle(new FontStyle().setTextSize(26))
                .setShowTableTitle(false)
                .setMinTableWidth(getWindowManager().getDefaultDisplay().getWidth());
//设置表格样式
        column2.setFormat(myFormat);
        column3.setFormat(myFormat);
        column4.setFormat(myFormat);
        columnlastDay.setFormat(myFormat);
        column5.setFormat(myFormat);
        column6.setFormat(myFormat);
        column7.setFormat(myFormat);
        column8.setFormat(myFormat);
        column9.setFormat(myFormat);
        column1.setFast(true);
        column2.setFast(true);
        column3.setFast(true);
        column4.setFast(true);
        columnlastDay.setFast(true);
        column5.setFast(true);
        column6.setFast(true);
        column7.setFast(true);
        column8.setFast(true);
        column9.setFast(true);
        column2.setTextAlign(Paint.Align.RIGHT);
        column3.setTextAlign(Paint.Align.RIGHT);
        column4.setTextAlign(Paint.Align.RIGHT);
        columnlastDay.setTextAlign(Paint.Align.RIGHT);
        column5.setTextAlign(Paint.Align.RIGHT);
        column6.setTextAlign(Paint.Align.RIGHT);
        column7.setTextAlign(Paint.Align.RIGHT);
        column8.setTextAlign(Paint.Align.RIGHT);
        column9.setTextAlign(Paint.Align.RIGHT);
        TableData<TVBaoGong> tableData = new TableData<>(null, list, column1, column2, column3, column4,columnlastDay, column5, column6, column7, column8, column9);
        table.setTableData(tableData);
    }

    private void loopSequence() {
        Disposable disposable = getDataFromServer()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        Log.d("lx", "loopSequence subscribe");
                    }
                })
                .doOnNext(new Consumer<HttpData<List<TVBaoGong>>>() {
                    @Override
                    public void accept(HttpData<List<TVBaoGong>> integer) throws Exception {
                        Log.d("lx", "loopSequence doOnNext: " + integer);
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(throwable.getMessage());
                    }
                })
                .delay(60, TimeUnit.SECONDS, true)       // 设置delayError为true，表示出现错误的时候也需要延迟5s进行通知，达到无论是请求正常还是请求失败，都是5s后重新订阅，即重新请求。
                .subscribeOn(Schedulers.io())
                .repeat()   // repeat保证请求成功后能够重新订阅。
                .retry()    // retry保证请求失败后能重新订阅
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<HttpData<List<TVBaoGong>>>() {
                    @Override
                    public void accept(HttpData<List<TVBaoGong>> integer) throws Exception {
                        // MapTableData tableData = MapTableData.create("表格名",JsonHelper.jsonToMapList(json));
                        TableData<TVBaoGong> tableData = new TableData<>(null, integer.getData(), column1, column2, column3, column4,columnlastDay, column5, column6, column7, column8, column9);
                        table.setTableData(tableData);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(throwable.getMessage());
                    }
                });
        compositeDisposable.add(disposable);
    }

    //主板查询
    private Observable<HttpData<List<TVBaoGong>>> getDataFromServer() {
        return Observable.create(new ObservableOnSubscribe<HttpData<List<TVBaoGong>>>() {
            @Override
            public void subscribe(ObservableEmitter<HttpData<List<TVBaoGong>>> emitter) throws Exception {
                if (emitter.isDisposed()) {
                    return;
                }
                EasyHttp.get(MainActivity.this)
                        .api(new TVBaoGongApi())
                        .request(new HttpCallback<HttpData<List<TVBaoGong>>>(MainActivity.this) {
                            @Override
                            public void onSucceed(HttpData<List<TVBaoGong>> result) {
                                //table.setData(result.getData());
                                emitter.onNext(result);
                                emitter.onComplete();
                            }

                            @Override
                            public void onFail(Exception e) {
                                emitter.onError(new Exception("连接网络失败" + e.getMessage()));
                                return;
                            }
                        });


            }
        });
    }

    private void loopSequence2() {
        Disposable disposable = getTVBaoGongTotalFromServer()
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        Log.d("lx", "loopSequence subscribe");
                    }
                })
                .doOnNext(new Consumer<HttpData<TVBaoGongTotal>>() {
                    @Override
                    public void accept(HttpData<TVBaoGongTotal> integer) throws Exception {
                        Log.d("lx", "loopSequence doOnNext: " + integer);
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(throwable.getMessage());
                    }
                })
                .delay(60, TimeUnit.SECONDS, true)       // 设置delayError为true，表示出现错误的时候也需要延迟5s进行通知，达到无论是请求正常还是请求失败，都是5s后重新订阅，即重新请求。
                .subscribeOn(Schedulers.io())
                .repeat()   // repeat保证请求成功后能够重新订阅。
                .retry()    // retry保证请求失败后能重新订阅
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<HttpData<TVBaoGongTotal>>() {
                    @Override
                    public void accept(HttpData<TVBaoGongTotal> integer) throws Exception {
                        // String.valueOf(integer.getData().get今日成品()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ",");

                        当前在转流转卡.setText(String.valueOf(integer.getData().get当前在产流转卡()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));
                        当前在产数量.setText(String.valueOf(integer.getData().get当前在产数量()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));
                        今日投产数量.setText(String.valueOf(integer.getData().get今日投产数量()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));
                        今日半成品完工数量.setText(String.valueOf(integer.getData().get今日半成品()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));
                        今日成品完工数量.setText(String.valueOf(integer.getData().get今日成品()).replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ","));

//                        当前在转流转卡.setText("当前在转流转卡:" + integer.getData().get当前在产流转卡());
//                        当前在产数量.setText("当前在产数量:" + integer.getData().get当前在产数量());
//                        今日投产数量.setText("今日投产数量:" + integer.getData().get今日投产数量());
//                        今日半成品完工数量.setText("今日半成品完工数量" + integer.getData().get今日半成品());
//                        今日成品完工数量.setText("今日成品完工数量" + integer.getData().get今日成品());
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd EEEE HH:mm", Locale.CHINA);
                        df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                        time.setText(df.format(System.currentTimeMillis()));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(throwable.getMessage());
                    }
                });
        compositeDisposable.add(disposable);
    }

    //边角查询
    private Observable<HttpData<TVBaoGongTotal>> getTVBaoGongTotalFromServer() {
        return Observable.create(new ObservableOnSubscribe<HttpData<TVBaoGongTotal>>() {
            @Override
            public void subscribe(ObservableEmitter<HttpData<TVBaoGongTotal>> emitter) throws Exception {
                if (emitter.isDisposed()) {
                    return;
                }
                EasyHttp.get(MainActivity.this)
                        .api(new TVBaoGongTotalApi())
                        .request(new HttpCallback<HttpData<TVBaoGongTotal>>(MainActivity.this) {
                            @Override
                            public void onSucceed(HttpData<TVBaoGongTotal> result) {
                                //table.setData(result.getData());
                                emitter.onNext(result);
                                emitter.onComplete();
                            }

                            @Override
                            public void onFail(Exception e) {
                                emitter.onError(new Exception("连接网络失败" + e.getMessage()));
                                return;
                            }
                        });


            }
        });
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycle;
    }

    @Override
    public void onSucceed(Object result) {

    }

    @Override
    public void onFail(Exception e) {

    }

    @Override
    protected void onStart() {

        compositeDisposable.dispose();
        compositeDisposable = new CompositeDisposable();
        loopSequence();
        loopSequence2();
        super.onStart();
    }

    @Override
    protected void onStop() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
        super.onStop();
    }
}
